package com.puyo;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;


/**
 * @author akash
 * Displays the menu pane containing all the menu options
 */
public class MenuPane extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;

	private JButton resumeGame;
	private JButton newGame;
	private JButton options;
	private JButton highScore;
	private JButton help;
	private JButton exit;
	private JPanel c;
	private JPanel menuPane;
	private JPanel bannerPan;
	private CardLayout cl;
	private Container cont;
	private PuyoPuyoGame ppg;
	private PaintPane p;
	@SuppressWarnings("unused")
	private boolean paused = false;
	private OptionPane op = new OptionPane(this);
	private JPanel highScorePan;
	private JPanel highScoreBanner;
	private JPanel scorePan;
	private JButton menu;
	private JButton menu1;
	private JPanel helpPane;
	private JTextArea ta;
	private JScrollPane sb;

	private String highScores[][] = new String[10][2];

	private JLabel scores[][] = new JLabel[10][2];

	public MenuPane(boolean paused) {
		this.paused = paused;
		c = new JPanel();
		menuPane = new JPanel();
		cont = getContentPane();
		cl = new CardLayout();
		cont.setLayout(cl);

		highScorePan = new JPanel();

		menuPane.setLayout(new BorderLayout());

		GridLayout gd = new GridLayout(paused ? 9 : 8, 3);
		gd.setVgap(4);
		gd.setHgap(4);
		c.setLayout(gd);

		resumeGame = new JButton("Resume Game");
		newGame = new JButton("New Game");
		options = new JButton("Options");
		highScore = new JButton("High Scores");
		help = new JButton("Help");
		exit = new JButton("Exit");

		addAL();
		constructMenu(paused);
		initBannerPan();
		menuPane.add(bannerPan, BorderLayout.NORTH);
		menuPane.add(c, BorderLayout.CENTER);

		initHighScoreBanner();
		initScorePan();
		initHighScoresArr();

		try {
			ta = new JTextArea(21, 20);
			readHighScores();
			readHelpFile();
		} catch (IOException e) {
			JOptionPane.showMessageDialog(c, "Error in reading file", "Error",
					JOptionPane.ERROR_MESSAGE);
		}
		setScoreLabels();
		addToScorePan();

		highScorePan.add(scorePan, BorderLayout.CENTER);

		sb = new JScrollPane(ta);

		menu1 = new JButton("Menu");
		menu1.addActionListener(this);

		initHelpPane();

		cont.add(menuPane, "card1");
		cont.add(highScorePan, "card2");
		cont.add(helpPane, "card3");

		setBounds(300, 50, 300, 438);
		setVisible(false);
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	/**
	 * Adds elements to scorepan
	 */
	private void addToScorePan() {
		scorePan.add(new JLabel(""));
		scorePan.add(new JLabel(""));

		menu = new JButton("Menu");
		menu.addActionListener(this);

		scorePan.add(menu);
		scorePan.add(new JLabel(""));
		scorePan.add(new JLabel(""));
		scorePan.add(new JLabel(""));
	}

	/**
	 * @param paused
	 * constructs the Menu pane and fills it with different buttons
	 */
	private void constructMenu(boolean paused) {

		if (paused) {
			c.add(new Label(""));
			c.add(resumeGame);
			c.add(new Label(""));
		}
		c.add(new Label(""));
		c.add(newGame);
		fillBlankLabel();
		c.add(options);
		fillBlankLabel();
		c.add(highScore);
		fillBlankLabel();
		c.add(help);
		fillBlankLabel();
		c.add(exit);
		for (int i = 0; i <= 9; i++)
			c.add(new Label(""));

	}

	/**
	 * Fills the space with blank labels
	 */
	private void fillBlankLabel() {
		for (int i = 0; i <= 1; i++) {
			c.add(new Label(""));
		}
	}

	/**
	 * Initializes the helpPane
	 */
	private void initHelpPane() {
		JPanel menuBut = new JPanel();
		menuBut.add(menu1);
		helpPane = new JPanel();
		helpPane.setLayout(new BorderLayout());
		helpPane.add(sb, BorderLayout.NORTH);
		helpPane.add(menuBut, BorderLayout.CENTER);
	}

	/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == resumeGame) {
			setVisible(false);
			ppg.setVisible(true);
			p.resumeGame();
		}
		if (e.getSource() == newGame) {
			setVisible(false);
			ppg = new PuyoPuyoGame();
		} else if (e.getSource() == options) {
			setVisible(false);
			op.setVisible(true);
		} else if (e.getSource() == highScore) {
			cl.show(cont, "card2");
		} else if (e.getSource() == exit) {
			System.exit(0);
		} else if (e.getSource() == menu) {
			cl.show(cont, "card1");
		} else if (e.getSource() == help) {
			cl.show(cont, "card3");
		} else if (e.getSource() == menu1) {
			cl.show(cont, "card1");
		}
	}

	/**
	 * @param menuPane2
	 * Adds all the ActionListener of all the buttons
	 */
	private void addAL() {
		resumeGame.addActionListener(this);
		newGame.addActionListener(this);
		options.addActionListener(this);
		highScore.addActionListener(this);
		help.addActionListener(this);
		exit.addActionListener(this);
	}

	/**
	 * @param name
	 * @param score
	 * Adds the corresponding score to the corresponding name
	 */
	public void addScore(String name, int score) {
		for (int i = 0; i < 10; i++) {
			String s;
			if (highScores[i][1].equals("")) {
				s = "-1";
			} else {
				s = highScores[i][1];
			}
			if (Integer.parseInt(s) < score) {
				moveScores(i);
				highScores[i][0] = name;
				highScores[i][1] = "" + score;
				try {
					writeHighScores();
				} catch (IOException e) {
					JOptionPane.showMessageDialog(c,
							"Error in writing into file", "Error",
							JOptionPane.ERROR_MESSAGE);
				}
				break;
			}
		}
	}

	/**
	 * Initialise the banner panel to show "puyo puyo"
	 */
	private void initBannerPan() {
		bannerPan = new JPanel();
		JLabel img = new JLabel("");
		img.setIcon(new ImageIcon("banner.png"));
		bannerPan.add(img);
	}

	/**
	 * Initialises the high score banner
	 */
	private void initHighScoreBanner() {
		highScoreBanner = new JPanel();
		JLabel img1 = new JLabel("");
		img1.setIcon(new ImageIcon("HighScoreBanner.png"));
		highScoreBanner.add(img1);
	}

	/**
	 * Initialises the array to store scores to zero
	 */
	private void initHighScoresArr() {
		for (int i = 0; i < 10; i++) {
			for (int j = 0; j < 2; j++) {
				highScores[i][j] = "";
			}
		}
	}

	/**
	 * Initialises the Name and score labels to scorePan
	 */
	private void initScorePan() {
		scorePan = new JPanel();
		scorePan.setLayout(new GridLayout(13, 3));
		scorePan.add(new JLabel(""));
		scorePan.add(new JLabel("Name"));
		scorePan.add(new JLabel("Score"));
	}

	/**
	 * @param index
	 * TO properly arrage the new scrorer on the score board
	 */
	public void moveScores(int index) {
		for (int i = 8; i >= index; i--) {

			highScores[i + 1][0] = highScores[i][0];
			highScores[i + 1][1] = highScores[i][1];

		}

	}

	/**
	 * @throws IOException
	 * Read the help file and display it on the help pane
	 */
	public final void readHelpFile() throws IOException {
		String s;
		BufferedReader readhelp = new BufferedReader(new FileReader(new File(
		"Readme.txt")));
		StringBuffer helpText = new StringBuffer();
		while ((s = readhelp.readLine()) != null) {
			helpText.append(s);
			helpText.append("\n");
		}
		readhelp.close();
		ta.setText(helpText.toString());
	}

	/**
	 * @throws IOException
	 * Read the High Score Card from the file
	 */
	public final void readHighScores() throws IOException {
		int i = 0;
		String s;
		BufferedReader br = new BufferedReader(new FileReader(new File(
		"HighScores.txt")));
		while ((s = br.readLine()) != null) {
			highScores[i][0] = s;
			highScores[i][1] = br.readLine();
			i++;
		}
		br.close();
	}

	/**
	 * @param p
	 * @param ppg
	 * Set the paint pane.
	 */
	public void setPaintPane(PaintPane p, PuyoPuyoGame ppg) {
		this.p = p;
		this.ppg = ppg;
	}

	/**
	 * Set the score label
	 */
	public final void setScoreLabels() {
		for (int i = 0; i < 10; i++) {
			scorePan.add(new JLabel("" + i));
			scorePan.add((scores[i][0] = new JLabel()));
			scorePan.add((scores[i][1] = new JLabel()));
		}

		for (int i = 0; i < 10; i++)
			for (int j = 0; j < 2; j++)
				scores[i][j].setText(highScores[i][j]);
	}

	/**
	 * @throws IOException
	 * Writes the score into a text file.
	 */
	public void writeHighScores() throws IOException {
		BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
		"HighScores.txt")));
		for (int i = 0; i < 10; i++) {
			bw.write(highScores[i][0]);
			bw.newLine();
			bw.write(highScores[i][1]);
			bw.newLine();
		}
		bw.flush();
		bw.close();
		setScoreLabels();
	}
}